<template>
  <div class="header">
    <div class="header-title">
      添加鲜花种类
    </div>
    <div class="header-content">
      id<input type="text" v-model="id">
      name<input type="text" v-model="name">
      <button @click="add" class="btnAdd">添加</button>
      关键字搜索:<input type="text" v-model="key"></div>
  </div>
  <table border=1 cellspacing="0" width="100%">
    <tr>
      <th>id</th>
      <th>name</th>
      <th>ctime</th>
      <th>operation</th>
    </tr>
    <tr v-show="item.name.indexOf(key)!=-1" v-for="(item,index) in list" :key="item.id">
      <td>{{item.id}}</td>
      <td>{{item.name}}</td>
      <td>{{item.ctime}}</td>
      <td>
        <button @click="del(index)" class="btndel">删除</button></td>
    </tr>
  </table>
</template>



<script  setup>
import {computed, ref} from "vue";

const list=ref([
  {id:1,name:'向日葵',ctime:new Date()},
  {id:2,name:'非洲菊',ctime:new Date()}
])
const id=ref("")
const name=ref("")
const key=ref("")

//tainjia
const add=()=>{
  if (id.value==''){
    alert('id不能为空')
    return
  }
  if(parseInt(id.value)<=0){
    alert("id不能为负数")
    return;
  }
  //NaN not a Number 不是一个数字
  if (isNaN(parseInt(id.value))){
    alert("id不为数字")
    return;
  }
  if (name.value==''){
    alert("name不能为空")
    return;
  }
  let found=false;
  list.value.some(item=>{
    if (item.id==id.value){
      found=true;
    }
  })
  if (found){
    alert("id已存在")
    return;
  }
  //向数组添记录
  list.value.push({id:id.value,name: name.value,ctime:new Date()})
}
const claerData=()=>{
  id.value=''
  name.value=''
}
//根据索引删除数据
const del=(index)=>{
  if (confirm("确定删除吗?"))
    list.value.splice(index,1)
}
//根据id删除数据
const delById=(id)=>{
  if (confirm("确定删除吗?"))
    list.value=list.value.some(item=>{
      if (item.id==id){
        list.value.splice(index,1)
      }
    })
}
const newList=computed(()=>{
  return list.value.filter(item=>{
    return item.name.includes(key.value)
  })
})
</script>


<!--scope:代表的是局部样式,只在当前页面有效,不写scoped代表全局有效-->
<style scoped>
.header{
  width: 100%;
  height: 70px;
  border:1px solid rgb(49, 124, 182);
  margin: 10px 0;
}
.header-title{
  width: 100%;
  height: 25px;
  color: white;
  background-color: rgb(49, 124, 182);
  box-sizing: border-box;
  padding-left: 10px;
  line-height: 25px;
}
.header-content{
  width: 100%;
  height: 45px;
  box-sizing: border-box;
  padding: 10px;
}
.btnAdd{
  background-color: #317CB6FF;
  color: white;
  margin: 0 5px;
}
.btndel{
  background-color: #317CB6FF;
  color: white;
  margin: 0 5px;
  cursor:pointer;
}

</style>